#include "keyPress.hpp"

static constexpr rt_base_t KEY0 = GET_PIN(E, 4);
static constexpr rt_base_t KEY1 = GET_PIN(E, 3);
static constexpr rt_base_t KEY2 = GET_PIN(E, 2);
static constexpr rt_base_t KEY_UP = GET_PIN(A, 0);

void KeyPress::run(void *parameter)
{
    this->keyInit();
    bool key0Pressed = false;
    bool key1Pressed = false;
    bool key0Last = false;
    bool key1Last = false;
    rt_uint16_t volSet = 0;
    vector<string> cmdVec;
    while (1)
    {
        key0Pressed = this->getKeyPress(KEY0);
        key1Pressed = this->getKeyPress(KEY1);
        if (key0Last && !key0Pressed) // press and release key0
        {
            volSet = volSet < 3995 ? volSet + 100 : 4095;
            cmdVec.clear();
            cmdVec.push_back("wr_fast");
            cmdVec.push_back(to_string(volSet));
            cmdVec.push_back(to_string(volSet));
            cmdVec.push_back(to_string(volSet));
            cmdVec.push_back(to_string(volSet));
            this->cmdMail->put(&cmdVec);
        }
        if (key1Last && !key1Pressed) // press and release key1
        {
            volSet = volSet > 100 ? volSet - 100 : 0;
            cmdVec.clear();
            cmdVec.push_back("wr_fast");
            cmdVec.push_back(to_string(volSet));
            cmdVec.push_back(to_string(volSet));
            cmdVec.push_back(to_string(volSet));
            cmdVec.push_back(to_string(volSet));
            this->cmdMail->put(&cmdVec);
        }
        key0Last = key0Pressed;
        key1Last = key1Pressed;
        rt_thread_mdelay(100);
    }
}

void KeyPress::keyInit()
{
    rt_pin_mode(KEY0, PIN_MODE_INPUT_PULLUP);
    rt_pin_mode(KEY1, PIN_MODE_INPUT_PULLUP);
    rt_pin_mode(KEY1, PIN_MODE_INPUT_PULLUP);
    rt_pin_mode(KEY_UP, PIN_MODE_INPUT_PULLDOWN);
}

bool KeyPress::getKeyPress(rt_base_t key)
{
    switch (key)
    {
    case KEY0:
        return rt_pin_read(key) == PIN_LOW;
    case KEY1:
        return rt_pin_read(key) == PIN_LOW;
    case KEY2:
        return rt_pin_read(key) == PIN_LOW;
    case KEY_UP:
        return rt_pin_read(key) == PIN_HIGH;
    default:
        return false;
    }
}
